package cn.com.yiqi.wsc.service.customer.impl;

import cn.com.yiqi.wsc.Ro.*;
import cn.com.yiqi.wsc.common.Result;
import cn.com.yiqi.wsc.common.ResultStatusEnum;
import cn.com.yiqi.wsc.common.ResultUtil;
import cn.com.yiqi.wsc.dao.balance.BalanceFetchDao;
import cn.com.yiqi.wsc.dao.balance.BalanceRecordDao;
import cn.com.yiqi.wsc.dao.balance.criteria.BalanceCriteria;
import cn.com.yiqi.wsc.dao.balance.entity.BalanceFetchEntity;
import cn.com.yiqi.wsc.dao.balance.entity.BalanceRecordEntity;
import cn.com.yiqi.wsc.dao.customer.*;
import cn.com.yiqi.wsc.dao.customer.criteria.CustomerCriteria;
import cn.com.yiqi.wsc.dao.customer.criteria.CustomerListCriteria;
import cn.com.yiqi.wsc.dao.lottery.LotteryRecordMapper;
import cn.com.yiqi.wsc.dao.order.OrderMainMapper;
import cn.com.yiqi.wsc.dao.order.criteria.OrderRecordCriteria;
import cn.com.yiqi.wsc.dao.point.PointRecordDao;
import cn.com.yiqi.wsc.dao.point.criteria.PointCriteria;
import cn.com.yiqi.wsc.dao.point.entity.PointRecordEntity;
import cn.com.yiqi.wsc.entity.customer.Customer;
import cn.com.yiqi.wsc.entity.customer.CustomerAuthorizationInfo;
import cn.com.yiqi.wsc.entity.customer.CustomerMention;
import cn.com.yiqi.wsc.entity.customer.CustomerSign;
import cn.com.yiqi.wsc.entity.order.OrderMain;
import cn.com.yiqi.wsc.service.customer.PortalCutomerService;
import cn.com.yiqi.wsc.service.user.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author 杨贵森
 * @ClassName:PortalCustomerImpl
 * @Title: PortalCustomerImpl
 * @Description: TODO
 * @date 2017/3/17
 */
@Service
public class PortalCustomerImpl implements PortalCutomerService {

    @Autowired
    CustomerMapper customerDao;
    @Autowired
    PointRecordDao pointRecordDao;
    @Autowired
    BalanceRecordDao balanceRecordDao;
    @Autowired
    CustomerAuthorizationInfoMapper customerAuthorizationDao;
    @Autowired
    CustomerAddressMapper customerAddressDao;
    @Autowired
    CustomerMentionDao customerMentionDao;
    @Autowired
    BalanceFetchDao balanceFetchDao;
    @Autowired
    CustomerSignMapper customerSignDao;
    @Autowired
    LotteryRecordMapper lotteryRecordDao;
    @Autowired
    OrderMainMapper orderMainDao;
    @Autowired
    CustomerFavorMapper customerFavorDao;
    @Autowired
    CartMapper cartDao;
    @Autowired
    UserService userService;
    /**
     * 判断用户是否存在并未被禁用
     * @param id 用户id
     * */
    @Override
    public Result<Customer> isExist(Integer id) {
        Result<Customer> re = new Result<Customer>();
        if(id == null){
            return ResultUtil.fail(re,"用户不存在或已被禁用");
        }
        Customer user = customerDao.isExist(id);
        if(null != user){
            re.putData("user",user);
            return ResultUtil.success(re);
        }else {
            return ResultUtil.fail(re,"用户不存在或已被禁用");
        }
    }

    /**
     * 查找用户基本信息
     * */
    public Customer selectById(Integer id){
        /*if(!ResultUtil.isSuccess(isExist(id))){
            return null;
        }*/
        return customerDao.selectByPrimaryKey(id);

    }

    @Override
    public Result findCustomerList(CustomerListCriteria customerListCriteria) {
        Result result = new Result();
        PageHelper.startPage(customerListCriteria.getCurrentPage(), customerListCriteria.getPageSize());
        PageHelper.orderBy("c.d_reg_time, c.n_id DESC");
        PageInfo<CustomerRo> customerList = new PageInfo<>(customerDao.selectCustomerList(customerListCriteria));
        result.putData("total",customerList.getTotal());
        result.putData("customerList",customerList.getList());
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        return result;
    }

    @Override
    @Transactional
    public Result updateCustomerStatus(CustomerCriteria  customerCriteria) {
        Result result = new Result();
        customerCriteria.setUpdateUserId(userService.getCurrentUserId());
        Integer status = customerDao.updateCustomerStatus(customerCriteria);
        result.putData("updateStatus",status);
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        return result;
    }
    @Override
    @Transactional
    public Result updateCustomerParam(CustomerRo customerRo) {
        Result result = new Result();
        customerRo.setUpdateUserId(userService.getCurrentUserId());
        result.putData("updateType",customerDao.updateCustomerParam(customerRo));
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        return result;
    }
    @Override
    @Transactional
    public Result deleteCustomer(CustomerCriteria  customerCriteria) {
        Result result = new Result();
        customerCriteria.setUpdateUserId(userService.getCurrentUserId());
        Integer status = customerDao.deletCustomerByCustomerId(customerCriteria);
        result.putData("deleteStatus",status);
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        return result;
    }


    /**
     * 获得当前客户和上级客户
     * @param userId
     * @return
     */
    @Override
    public Result findCustomerAndHigherCustomer(Integer userId) {
        Result result = new Result();
        Customer currentCustomer = selectById(userId);
        Map<String, Object> customerMap = new HashMap<>();

        customerMap.put("currentCustomer",currentCustomer);
        if(currentCustomer!=null){
            currentCustomer.setName(null);
            if(currentCustomer.getPid()!=null  && !currentCustomer.getPid().equals("") && currentCustomer.getPid()!=0 ){
                Customer higherCustomer = selectById(currentCustomer.getPid());
                if(higherCustomer!=null){
                    customerMap.put("higherCustomerName",higherCustomer.getNick());
                    customerMap.put("higherCustomerTel",higherCustomer.getTel());
                }

            }
        }
        result.setData(customerMap);
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        return result;
    }

    @Override
    public Result findCustomerInfo(Integer userId) {
        Result result = new Result();
        Customer currentCustomer = selectById(userId);
        Map<String, Object> customerMap = new HashMap<>();
        Long countPointExchangeBalance = pointRecordDao.countExchangePoint((long) userId,null, null, 5);
        Long  countBalanceToCash =balanceRecordDao.countBalanceToCash((long) userId,3);
        CustomerAuthorizationInfo customerAuthorizationInfo  = customerAuthorizationDao.selectByPrimaryKey(userId);

        customerMap.put("Customer",currentCustomer);

        if(customerAuthorizationInfo !=null){
            customerMap.put("identify",customerAuthorizationInfo.getLoginAccount());
        }

        customerMap.put("countPointExchangeBalance",countPointExchangeBalance);
        customerMap.put("countBalanceToCash",countBalanceToCash);


        result.setData(customerMap);
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        return result;
    }

    @Override
    public Result findCustomerAddress(CustomerCriteria customerCriteria) {
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        PageHelper.startPage(customerCriteria.getCurrentPage(), customerCriteria.getPageSize());
        PageHelper.orderBy("d.n_id  DESC");
        PageInfo<SimpleAddressVO> simpleAddressList = new PageInfo<>(customerAddressDao.findSimpleAddress(customerCriteria.getCustomerId()));
        result.putData("total",simpleAddressList.getTotal());
        result.putData("addressList",simpleAddressList.getList());
        return result;
    }

    @Override
    public Result findCustomerMentions(CustomerCriteria customerCriteria) {

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        PageHelper.startPage(customerCriteria.getCurrentPage(), customerCriteria.getPageSize());
        PageHelper.orderBy("n_id  ASC");
        PageInfo<CustomerMention> customerMentionsList = new PageInfo<>(customerMentionDao.selectByCustomerId(customerCriteria.getCustomerId()));
        result.putData("total",customerMentionsList.getTotal());
        result.putData("mentionsList",customerMentionsList.getList());
        return result;
    }


    @Override
    public Result findCustomerPointDetail(PointCriteria pointCriteria){

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        PageHelper.startPage(pointCriteria.getCurrentPage(), pointCriteria.getPageSize());
        PageInfo<PointDetailVO> customerPointDetailList = new PageInfo<>(pointRecordDao.selectPointDetail(pointCriteria));
        result.putData("total",customerPointDetailList.getTotal());
        result.putData("pointList",customerPointDetailList.getList());
        return result;
    }

    @Override
    public Result findCustomerBalanceDetail(BalanceCriteria balanceCriteria){

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        PageHelper.startPage(balanceCriteria.getCurrentPage(), balanceCriteria.getPageSize());
        PageInfo<BalanceRecordEntity> customerBalanceDetailList = new PageInfo<>(balanceRecordDao.selectBalanceDetail(balanceCriteria));
        result.putData("total",customerBalanceDetailList.getTotal());
        result.putData("BalanceList",customerBalanceDetailList.getList());
        return result;
    }

    @Override
    public Result findCustomerBalanceFetchDetail(BalanceCriteria balanceCriteria){

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        PageHelper.startPage(balanceCriteria.getCurrentPage(), balanceCriteria.getPageSize());
        PageInfo<BalanceFetchEntity> customerBalanceFetchDetailList = new PageInfo<>(balanceFetchDao.selectBalanceFetchDetailList(balanceCriteria));
        result.putData("total",customerBalanceFetchDetailList.getTotal());
        result.putData("BalanceFetchList",customerBalanceFetchDetailList.getList());
        return result;
    }

    @Override
    public Result findCustomerSignedDetail(CustomerCriteria customerCriteria){

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        PageHelper.startPage(customerCriteria.getCurrentPage(), customerCriteria.getPageSize());
        PageInfo<CustomerSign> customerSignedDetailList = new PageInfo<>(customerSignDao.selectByCustomerId(customerCriteria));
        result.putData("total",customerSignedDetailList.getTotal());
        result.putData("signedList",customerSignedDetailList.getList());
        return result;
    }

    @Override
    public Result findCustomerLotteryDetail(CustomerCriteria customerCriteria){

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        PageHelper.startPage(customerCriteria.getCurrentPage(), customerCriteria.getPageSize());
        PageInfo<PortalLotteryRecordVO> customerLotteryDetailList = new PageInfo<>((lotteryRecordDao.selectLotteryRecord(customerCriteria)));
        result.putData("total",customerLotteryDetailList.getTotal());
        result.putData("lotteryList",customerLotteryDetailList.getList());
        return result;
    }

    @Override
    public Result findCustomerOrderDetail(OrderRecordCriteria orderRecordCriteria){

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        PageHelper.startPage(orderRecordCriteria.getCurrentPage(), orderRecordCriteria.getPageSize());
        PageInfo<OrderMain> customerOrderDetailList = new PageInfo<>(orderMainDao.selectOrderDetail(orderRecordCriteria));
        result.putData("total",customerOrderDetailList.getTotal());
        result.putData("orderList",customerOrderDetailList.getList());
        return result;
    }

    @Override
    public Result findCustomerFavorDetail(CustomerCriteria customerCriteria){

        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        PageHelper.startPage(customerCriteria.getCurrentPage(), customerCriteria.getPageSize());
        PageInfo<CustomerFavorVO> customerFavorDetailList = new PageInfo<>(customerFavorDao.selectFavorList(customerCriteria.getCustomerId()));
        result.putData("total",customerFavorDetailList.getTotal());
        result.putData("favorList",customerFavorDetailList.getList());
        return result;
    }

    @Override
    public Result findCustomerCartDetail(CustomerCriteria customerCriteria){
        Result result = new Result();
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        PageHelper.startPage(customerCriteria.getCurrentPage(), customerCriteria.getPageSize());
        PageInfo<CartVO> customerOrderDetailList = new PageInfo<>(cartDao.selectCartByCustomerId(customerCriteria.getCustomerId()));
        result.putData("total",customerOrderDetailList.getTotal());
        result.putData("cartList",customerOrderDetailList.getList());
        return result;
    }

    @Override
    public Result findCustomerDistributionList(CustomerListCriteria customerListCriteria) {
        Result result = new Result();
        Customer customer =customerDao.selectByPrimaryKey(customerListCriteria.getId());
        customerListCriteria.setSeq(customer.getSeq());
        Integer length = customer.getSeq().length();
        PageHelper.startPage(customerListCriteria.getCurrentPage(), customerListCriteria.getPageSize());

        PageInfo<SimpleDistributionVO> distributionList = new PageInfo<>(customerDao.selectBySeq(customerListCriteria));
        List<SimpleDistributionVO> simpleDistributionVOList = distributionList.getList();
        for(SimpleDistributionVO simpleDistributionVO :simpleDistributionVOList){
            simpleDistributionVO.setLevel((simpleDistributionVO.getLevel()-length)/2);

        }
        result.putData("total",simpleDistributionVOList.size());
        result.putData("distributionList",simpleDistributionVOList);
        result.setStatus(ResultStatusEnum.操作成功.getCode());
        return result;
    }

    @Override
    public Result insertPresentPoint(PointRecordEntity pointRecordEntity){

        Result result = new Result();
        Customer  customer =customerDao.selectByPrimaryKey(pointRecordEntity.getCustomerId().intValue());

        pointRecordEntity.setBeforePoint(customer.getPoint());
        pointRecordEntity.setAfterPoint(customer.getPoint()+pointRecordEntity.getPoint());
        pointRecordEntity.setUsePoint(0);
        pointRecordEntity.setOperateType(1);
        pointRecordEntity.setBizType(6);
        pointRecordEntity.setStatus(1);
        pointRecordEntity.setStartTime(new Date());
        pointRecordEntity.setInsertTime(new Date());
        pointRecordEntity.setInsertUserId(userService.getCurrentUserId());
        customer.setPoint(pointRecordEntity.getPoint());
        customerDao.updateCustomerPointByCustomerId(customer);

        result.setStatus(ResultStatusEnum.操作成功.getCode());
        result.putData("presentPointStatus",pointRecordDao.insert(pointRecordEntity));
        return result;
    }


}
